package com.code.soulqlexpress.func;

import com.ql.util.express.ArraySwap;
import com.ql.util.express.InstructionSetContext;
import com.ql.util.express.OperateData;
import com.ql.util.express.OperatorOfNumber;
import com.ql.util.express.instruction.op.OperatorBase;

import java.math.BigDecimal;

/**
 * @author yzh
 * @date 2020/1/17
 * @Content: 去除null,求平均值
 */
public class AvgOperator extends OperatorBase {

    @Override
    public OperateData executeInner(InstructionSetContext instructionSetContext, ArraySwap arraySwap) throws Exception {
        int length = arraySwap.length;
        Object sum = 0;
        int count = 0;
        for (int i = 0; i < length; i++) {
            OperateData operateData = arraySwap.get(i);
            Object object = operateData.getObject(instructionSetContext);
            if (null == object) {
                continue;
            }
            count++;
            sum = OperatorOfNumber.add(sum, object, this.isPrecise);
        }
        //全部为null
        if (count == 0) {
            return null;
        }

        double sumDouble = 0;
        if (sum instanceof Integer) {
            sumDouble = ((Integer) sum).doubleValue();
        } else {
            sumDouble = ((BigDecimal) sum).doubleValue();
        }

        return new OperateData(sumDouble / count * 1.0, Double.class);
    }
}
